package org.esisar.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import org.esisar.model.Album;
import org.esisar.model.Model;

public class AlbumStatementCreator implements StatementCreator{


	private PreparedStatement preparedStatement;
	
	@Override
	public PreparedStatement addStatement(Connection connection, Model model) throws SQLException {
		
		Album album = modelToAlbum(model);
			
		preparedStatement = connection.prepareStatement("INSERT INTO album (idAlbum,idClient,title,subtitle,shared) VALUES(album_sequence.nextval,?,?,?,?)");

		fillModel(album);
	
		return preparedStatement;
		
	}

	@Override
	public PreparedStatement deleteStatement(Connection connection, List<Long> keys) throws SQLException {

		preparedStatement = connection.prepareStatement("DELETE FROM album WHERE idAlbum=?");

		preparedStatement.setLong(1, keys.get(0));
				
		return preparedStatement;
	}

	@Override
	public PreparedStatement updateStatement(Connection connection, Model model) throws SQLException {
		
		Album album = modelToAlbum(model);
		
		preparedStatement = connection.prepareStatement("UPDATE album SET title = ?, subtitle = ?, shared = ? WHERE idAlbum = ?");

		fillModel(album);
		preparedStatement.setLong(4, album.getIdAlbum());
		
		return preparedStatement;
	}

	private void fillModel(Album album) throws SQLException {
		
		preparedStatement.setString(1, album.getIdClient()+"");
		preparedStatement.setString(2, album.getTitle());
		preparedStatement.setString(3, album.getSubTitle());
		preparedStatement.setBoolean(4, album.isShared());
	}

	private Album modelToAlbum(Model model) {
		Album album;
		
		if (model instanceof Album){
			album = (Album) model;
		}else{
			throw new ClassCastException("Bad object instance");
		}
		return album;
	}
	
	@Override
	public PreparedStatement readStatement(Connection connection, String field,
			String value) throws SQLException {
		preparedStatement = connection.prepareStatement("select * from album where " + field + " = ? ");

		preparedStatement.setString(1, value);
		
		return preparedStatement;
	}

	@Override
	public Model fillModel(ResultSet rs) throws SQLException {
		String idAlbum = rs.getString("idAlbum");
		String idClient = rs.getString("idClient");
		String title = rs.getString("title");
		String subTitle = rs.getString("subtitle");
		boolean shared = rs.getBoolean("shared");
		
		Album album = new Album(Long.parseLong(idClient), title, subTitle, shared);
		album.setIdAlbum(Long.parseLong(idAlbum));
		
		return album;
	}
}
